const { isMainThread, parentPort, workerData } = require('worker_threads')
const mysql = require('mysql2/promise');
const dbhealper = require('../utils/dbhealper');
const axiosUitl = require("../utils/axios");

if (isMainThread) {
    return
}

const runWorker = async () => {
    setTimeout(() => {
        runWorker()
    }, 60 * 60 * 1000 + 1000);
    const conn = await mysql.createConnection(dbhealper.config)
    let [results, fields] = await conn.query("select * from timefarm where id>0")
    // 一次10个并行
    let index = 0
    let step = 10
    while (index < results.length) {
        try {
            let promises = []
            for (let i = index; i < index + step; i++) {
                if (i >= results.length) {
                    break;
                }
                const element = results[i]
                if (element.params == null || element.params.length == 0) {
                    continue
                }
                const unit = new TimefarmUnit(element, conn)
                const prms = unit.run()
                promises.push(prms)
            }
            await Promise.allSettled(promises)
            console.log(Date() + " finished " + index + "..<" + (index + step))
            index += step
        } catch (error) {
            console.error(error)
            continue
        }
    }
    // 10分钟后递归回调
    await conn.end();
}

class TimefarmUnit {
    constructor(tokenInfo, sqlconn) {
        this.tokenInfo = tokenInfo
        this.sqlconn = sqlconn
    }

    async run() {
        try {
            const proxy = axiosUitl.parseProxy(this.tokenInfo.proxy)
            const axios = axiosUitl.createAxios(proxy, axiosUitl.createHeader())
            // 获取token
            if (this.authToken == null) {
                // const tempParams = "query_id=AAERjxg6AwAAABGPGDqWO_0X&user=%7B%22id%22%3A7417138961%2C%22first_name%22%3A%22Leleene%22%2C%22last_name%22%3A%22Venkent%22%2C%22username%22%3A%22LeleeneVenkent%22%2C%22language_code%22%3A%22es%22%2C%22allows_write_to_pm%22%3Atrue%7D&auth_date=1719413032&hash=fb5b178c4c9e4bab5bf2edbdf82823dc515e207570aef0edd2f531a4b83a7b60";
                const tempParams = this.tokenInfo.params
                const authResp = await axios.request('https://tg-bot-tap.laborx.io/api/v1/auth/validate-init', {
                    data: tempParams,
                    method: 'post',
                    headers: {
                        'accept': 'application/json, text/plain, */*',
                        'content-type': 'text/plain;charset=UTF-8',
                    }
                })
                const authData = authResp.data
                const authToken = authData.token;
                this.authToken = authToken
                // console.log('获取token')
            }
            const headers = {
                'authorization': 'Bearer ' + this.authToken,
            }
            // 获取info是否在挖矿
            const infoResp = await axios.request('https://tg-bot-tap.laborx.io/api/v1/farming/info', {
                headers,
            })

            // console.log('查询info')
            // info.activeFarmingStartedAt == null 可以开始挖矿
            if (infoResp.data.activeFarmingStartedAt == null) {
                // 开始farming
                const farmResp = await axios.request('https://tg-bot-tap.laborx.io/api/v1/farming/start', {
                    method: 'post',
                    headers,
                })
                // console.log('开始挖矿')
            } else {
                const farmingDate = Date.parse(infoResp.data.activeFarmingStartedAt)
                const dateNow = Date.now()
                if (dateNow - farmingDate > infoResp.data.farmingDurationInSec * 1000) {
                    // 挖矿完成
                    const finishResp = await axios.request('https://tg-bot-tap.laborx.io/api/v1/farming/finish', {
                        method: 'post',
                        headers,
                    })
                    // console.log('完成挖矿')
                    // 重启挖矿
                    // 开始farming
                    const farmResp = await axios.request('https://tg-bot-tap.laborx.io/api/v1/farming/start', {
                        method: 'post',
                        headers,
                    })
                    // console.log('重新开始挖矿')
                } else {
                    // console.log('挖矿进行中...')
                }
            }
            // 3. 收割朋友
            try {
                await axios.request("https://tg-bot-tap.laborx.io/api/v1/balance/referral/claim", {
                    method: "post",
                    headers
                })
            } catch (error) {
                // 没法收割？Do Nothing
            }
            // 4. 自动升级
            // 5. 查余额并入库
            const balanceResp = await axios.request("https://tg-bot-tap.laborx.io/api/v1/balance", {
                method: "get",
                headers
            })
            const balance = balanceResp.data.balance
            await this.sqlconn.query("update timefarm set score=? where id=?", [balance, this.tokenInfo.id])
        } catch (error) {
            console.error(error)
        }
    }
}

runWorker();